package com.wowangz.cms.dailyoperation.servicemanage.api;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.common.utils.MathUtils;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.servicemanage.pojo.Charge;
import com.wowangz.cms.dailyoperation.servicemanage.pojo.StoreChargeManage;
import com.wowangz.cms.dailyoperation.servicemanage.service.SysServiceInfoService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.exception.ServiceException;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.databaseresource.pojo.DatabaseResource;
import com.wowangz.cms.systemmanage.databaseresource.service.DatabaseBindingService;


@SuppressWarnings("unchecked")
@Scope("prototype")
@Controller
public class ServiceManageController extends BaseController {

	/**
	 * 进入选择商户菜单
	 * @param request
	 * @param model
	 * @return 
	 * 
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/toselectStoreMenu.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String toselectStoreMenu(HttpServletRequest request, Model model) {
		
		return "/WEB-INF/jsp/dailyoperation/servicemanage/serviceSelect";
	}
	
	/**
	 * 商户进入服务购买菜单
	 * @param request
	 * @param model
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dailyoperation/servicemanage/servicelist.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String create(HttpServletRequest request, Model model) {
		String id = request.getParameter("id");
		String name = "";
		try {
			name = java.net.URLDecoder.decode(request.getParameter("name"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		};
		
		List list=getChargeForList(Long.parseLong(id));
		request.setAttribute("name", name);
		request.setAttribute("servicelist", list);
		request.setAttribute("storeid", id);
		return "/WEB-INF/jsp/dailyoperation/servicemanage/servicebuy";
	}
	/*********************
	 * 服务管理-服务购买  支付按钮  保存数据
	 * @param request
	 * @param response
	 * @param model
	 * @throws ServiceException
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/savesService.json", method = {RequestMethod.GET,RequestMethod.POST})
	public void savesService(HttpServletRequest request,HttpServletResponse response, Model model) throws ServiceException{
		Connection conn_service=null;
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,true);
		try {
			String data = request.getParameter("type");
			String tranCode = request.getParameter("tranCode");
			Long storeid = Long.parseLong(request.getParameter("storeid"));
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,false);
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("storeid", storeid);
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			hashMap.put("state", SysConstant.CommonApproveStatus.OK);
			DatabaseResource databaseResource = databaseBindingService.queryDatabaseBinding(hashMap);
			if(databaseResource == null){
				//商户若没挂接数据源，则提示
				userContext.setErrorMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
				throw new ServiceException(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
			}else{
				if(data!=null && !("").equals(data)){
					String[] data1=data.split("##");
					if(data1.length>0){
						Charge charge=new Charge();
						charge.setStoreid(storeid);
						charge.setTranscode(tranCode);
						charge.setStatusid(SysConstant.RecordStatus.VALID);
						charge.setInputuserid(userContext.getLoginUser().getId());
						charge.setInputusername(userContext.getLoginUser().getUsername());
						charge.setModifyuserid(userContext.getLoginUser().getId());
						charge.setModifyusername(userContext.getLoginUser().getUsername());
						charge.setBuytype(SysConstant.ServiceBuyType.OTHER_BUY);
						charge.setBuyname(userContext.getLoginUser().getUsername());
						charge.setUsestatus(SysConstant.ServiceBuyUsestatus.VALID_BUY);
						//返回执行insertSysServiceByConn完成后的Connection对象
						conn_service = sysServiceInfoService.insertSysServiceByConn(charge);
						//从redis中获取所有的服务及价格
						List<Charge> redisList=getChargeForList(storeid);
						for (int i = 0; i < data1.length; i++) {
							if(data1[i]!=null && !("").equals(data1[i])){
								StoreChargeManage storeChargeManage=new StoreChargeManage();
								String[] saveData=data1[i].split(":");
								String trantype=saveData[0];
								Long id=Long.valueOf(saveData[1]);
								String num=saveData[2];
								Charge chargeMap=null;
								for(Charge chargeList:redisList){
									if(chargeList.getServiceid()==id){
										chargeMap=chargeList;
										break;
									}
								}
								storeChargeManage.setStatusid(SysConstant.ServiceBuyUsestatus.VALID_BUY);
								storeChargeManage.setInputtime(new Date());
								storeChargeManage.setInputusername(userContext.getLoginUser().getUsername());
								storeChargeManage.setModifyusername(userContext.getLoginUser().getUsername());
								storeChargeManage.setModifytime(new Date());
								storeChargeManage.setMainid(charge.getId());
								storeChargeManage.setServiceid(Long.valueOf(id));
								storeChargeManage.setServicename(chargeMap.getServicename());
								storeChargeManage.setBuycount(Long.valueOf(num));
								if(Long.valueOf(trantype)==SysConstant.ChargeManage.MONTH){
									//按月
									storeChargeManage.setBuytype(SysConstant.ChargeManage.CIRCLE);
									Date startdate=DataFormat.parseDate(saveData[3],DataFormat.DT_YYYY_MM_DD);
									Date enddate=DataFormat.calculationSubtractionDate(startdate,Integer.valueOf(num), 2);
									storeChargeManage.setStartdate(startdate);
									storeChargeManage.setEnddate(enddate);
									storeChargeManage.setUnitprice(chargeMap.getMonthprice());
									storeChargeManage.setStoreid(storeid);
									storeChargeManage.setTotalprice(MathUtils.mul(storeChargeManage.getBuycount(),storeChargeManage.getUnitprice()));
									//验证 该商户 是否已经购买 同一个服务在 同一个日期期间内的服务
									Map<String, Object> map =new HashMap<String, Object>();
									map.put("storeid", storeid);
									map.put("serviceid",storeChargeManage.getServiceid());
									map.put("buytype", storeChargeManage.getBuytype());
									map.put("datetime",startdate);
									map.put("statusid",SysConstant.RecordStatus.VALID);
									boolean flag =sysServiceInfoService.findChargeManageForListByConn(map);
									if(flag){
										//如果存在有购买相同服务，将conn_service连接对象的事物回滚
										conn_service.rollback();
										userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.ordermessage.erroralert"));
									}else{
										//否则就新增购买的服务
										conn_service = sysServiceInfoService.insertSysServiceDetailByConn(storeChargeManage,conn_service);
									}
								}else if(Long.valueOf(trantype)==SysConstant.ChargeManage.TRADESUM){
									//按笔数
									storeChargeManage.setBuytype(SysConstant.ChargeManage.TRADE);
									storeChargeManage.setUnitprice(chargeMap.getProposedprice());
									storeChargeManage.setTotalprice(MathUtils.mul(storeChargeManage.getBuycount(),storeChargeManage.getUnitprice()));
									conn_service = sysServiceInfoService.insertSysServiceDetailByConn(storeChargeManage,conn_service);
								}else{
									conn_service.rollback();
									System.out.println("未知收费方式不处理");
								}
							}
						}
						//最后都操作完毕，关闭连接对象
						sysServiceInfoService.setAutoCommitAndClose(conn_service);
						//判断是否有错误提示
						if (userContext.getMessageType() != 2) {
							// 修改金额
							SysServiceInfoService querySysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
							Map<String, Object> map = new HashMap<String, Object>();
							map.put("mainid", charge.getId());
							map.put("storeid", storeid);
							double amount = querySysServiceInfoService.findTotalAmountByConn(map);
							Charge saveCharge = new Charge();
							saveCharge.setStoreid(storeid);
							saveCharge.setAmount(amount);
							saveCharge.setId(charge.getId());
							querySysServiceInfoService.updateSysServiceByConn(saveCharge);
							userContext.setCloseWindow(true);
							userContext.setInfoMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.success"));
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.ordermessage.error")+","+e.getMessage());
		}finally{
			try {
				sysServiceInfoService.close(conn_service,null, null,null);
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 服务管理-购买服务  获得结束日期
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/queryServicebuyForDate.json", method = {RequestMethod.GET,RequestMethod.POST })
	public void queryServicebuyForDate(HttpServletRequest request, HttpServletResponse response) {
		try {
			String startDate=request.getParameter("startdate");
			Integer monlen=Integer.valueOf(request.getParameter("num"));
			if(startDate.length()==10){
				Date enddate=DataFormat.calculationSubtractionDate(DataFormat.parseDate(startDate,DataFormat.DT_YYYY_MM_DD),monlen,2);
				response.getWriter().write("{\"info\":\"" + DataFormat.formatDate(enddate,DataFormat.DT_YYYY_MM_DD) + "\"}");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 服务管理-订单记录 页面
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/recordlist.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String recordlist(HttpServletRequest request, Model model) {
		return "/WEB-INF/jsp/dailyoperation/servicemanage/servicelist";
	}
	/**
	 * 服务管理-订单记录 查询列表
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/queryOrderMessageListInfoDataGrid.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void getOrderMessageDataGridJson(HttpServletRequest request, HttpServletResponse response) {
		SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
		try {
			final PangingParam pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request,PangingParam.class);
			final Map<String, Object> map = ServletUtils.getParametersToHashMap(request);
			final DataGrid dataGrid = new DataGrid();
			long resultCount = 0;
			List<Charge> resultList = new ArrayList<Charge>();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid",SysConstant.RecordStatus.VALID);
			if(map.get("enddate")!=null && map.containsKey("enddate")){
				Date tsDate=DataFormat.parseDate(map.get("enddate").toString(),DataFormat.DT_YYYY_MM_DD);
				map.put("enddate",DataFormat.formatDate(DataFormat.getNextDate(tsDate,1),DataFormat.DT_YYYY_MM_DD));
			}
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,true);
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("storeid", map.get("storeid"));
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			hashMap.put("state", SysConstant.CommonApproveStatus.OK);
			DatabaseResource databaseResource = databaseBindingService.queryDatabaseBinding(hashMap);
			if(databaseResource != null){
				resultCount = sysServiceInfoService.findResultCountByConn(map);
				resultList = sysServiceInfoService.findResultListByConn(map);
			}
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("transcode", DataTypeConstant.STRING);// 流水号
			dataStyle.addDepict("transtime", DataTypeConstant.DATETIME);// 支付日期
			dataStyle.addDepict("amount",DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("storeid", DataTypeConstant.LONG);
			dataStyle.addDepict("usestatusname", DataTypeConstant.STRING);
			dataStyle.addDepict("buyname", DataTypeConstant.STRING);
			dataStyle.addDepict("refundamount", DataTypeConstant.AMOUNT_2);
			dataStyle.addDepict("inputusername", DataTypeConstant.STRING);
			DataResult dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 服务管理-订单记录 详细页面
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/serviceBuyView.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String serviceBuyView(HttpServletRequest request, Model model) {
		try {
			SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
			String id=request.getParameter("applyId");
			String storeid=request.getParameter("storeid");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("mainid",id);
			map.put("storeid",storeid);
			List<StoreChargeManage> list=sysServiceInfoService.findStoreChargeManageForListByConn(map);
			List<Charge> reslist = new ArrayList<Charge>();
			Double countAmount=0.00,monthAmount=0.00;
			int countNum=0,monthNum=0;
			for (StoreChargeManage storeChargeManage:list) {
				Charge chargedata =new Charge();
				chargedata.setBuycount(storeChargeManage.getBuycount());
				if(SysConstant.ChargeManage.TRADE==storeChargeManage.getBuytype()){
					//笔数
					chargedata.setIsmonth(SysConstant.YesOrNo.NO);
					chargedata.setIsproposed(SysConstant.YesOrNo.YES);
					chargedata.setProposedprice(storeChargeManage.getUnitprice());
					countAmount+=storeChargeManage.getTotalprice();
					countNum+=storeChargeManage.getBuycount();	
				}else if(SysConstant.ChargeManage.CIRCLE==storeChargeManage.getBuytype()){
					//按月
					chargedata.setIsmonth(SysConstant.YesOrNo.YES);
					chargedata.setIsproposed(SysConstant.YesOrNo.NO);
					chargedata.setMonthprice(storeChargeManage.getUnitprice());
					chargedata.setStartdate(DataFormat.formatDate(storeChargeManage.getStartdate(), DataFormat.DT_YYYY_MM_DD));
					chargedata.setEnddate(DataFormat.formatDate(storeChargeManage.getEnddate(), DataFormat.DT_YYYY_MM_DD));
					monthAmount+=storeChargeManage.getTotalprice();
					monthNum+=storeChargeManage.getBuycount();
				}
				chargedata.setServiceid(storeChargeManage.getServiceid());
				chargedata.setServicename(storeChargeManage.getServicename());
				reslist.add(chargedata);
			}
			request.setAttribute("countAmount",DataFormat.formatAmount(countAmount,2));
			request.setAttribute("monthAmount",DataFormat.formatAmount(monthAmount,2));
			request.setAttribute("countNum",countNum);
			request.setAttribute("monthNum",monthNum);
			request.setAttribute("totalAmount",DataFormat.formatAmount(MathUtils.add(countAmount, monthAmount),2));
			request.setAttribute("servicelist", reslist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/servicemanage/serviceview";
	}
	
	/**
	 * 服务管理-订单记录 修改页面  只能修改开始日期
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/serviceBuyModify.web", method = {RequestMethod.GET,RequestMethod.POST})
	public String serviceBuyModify(HttpServletRequest request, Model model) {
		try {
			SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
			String id=request.getParameter("applyId");
			String storeid=request.getParameter("storeid");
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("mainid",id);
			map.put("storeid",storeid);
			List<StoreChargeManage> list=sysServiceInfoService.findStoreChargeManageForListByConn(map);
			List<Charge> reslist = new ArrayList<Charge>();
			map.put("storeid",storeid);
			map.put("statusid",SysConstant.RecordStatus.VALID);
			map.put("id",id);
			Charge charge=sysServiceInfoService.findResultOneByConn(map);
			Double countAmount=0.00,monthAmount=0.00;
			int countNum=0,monthNum=0;
			for (StoreChargeManage storeChargeManage:list) {
				Charge chargedata =new Charge();
				chargedata.setBuycount(storeChargeManage.getBuycount());
				if(SysConstant.ChargeManage.TRADE==storeChargeManage.getBuytype()){
					//笔数
					chargedata.setIsmonth(SysConstant.YesOrNo.NO);
					chargedata.setIsproposed(SysConstant.YesOrNo.YES);
					chargedata.setProposedprice(storeChargeManage.getUnitprice());
					countAmount=MathUtils.add(storeChargeManage.getTotalprice(),countAmount);
					countNum=(int) MathUtils.add(storeChargeManage.getBuycount(),countNum);	
				}else if(SysConstant.ChargeManage.CIRCLE==storeChargeManage.getBuytype()){
					//按月
					chargedata.setIsmonth(SysConstant.YesOrNo.YES);
					chargedata.setIsproposed(SysConstant.YesOrNo.NO);
					chargedata.setMonthprice(storeChargeManage.getUnitprice());
					chargedata.setStartdate(DataFormat.formatDate(storeChargeManage.getStartdate(), DataFormat.DT_YYYY_MM_DD));
					chargedata.setEnddate(DataFormat.formatDate(storeChargeManage.getEnddate(), DataFormat.DT_YYYY_MM_DD));
					monthAmount=MathUtils.add(storeChargeManage.getTotalprice(),monthAmount);
					monthNum=(int) MathUtils.add(storeChargeManage.getBuycount(),monthNum);	
				}
				chargedata.setServiceid(storeChargeManage.getServiceid());
				chargedata.setServicename(storeChargeManage.getServicename());
				reslist.add(chargedata);
			}
			request.setAttribute("countAmount",DataFormat.formatAmount(countAmount,2));
			request.setAttribute("monthAmount",DataFormat.formatAmount(monthAmount,2));
			request.setAttribute("countNum",DataFormat.formatNumber(countNum,0));
			request.setAttribute("monthNum",DataFormat.formatNumber(monthNum,0));
			request.setAttribute("storeid",storeid);
			request.setAttribute("mainid",charge.getId());
			request.setAttribute("transcode",charge.getTranscode());
			request.setAttribute("totalAmount",DataFormat.formatAmount(MathUtils.add(countAmount, monthAmount),2));
			request.setAttribute("servicelist", reslist);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/servicemanage/serviceupdate";
	}
	private boolean saveService(String data,Long storeid,String tranCode,SysServiceInfoService sysServiceInfoService,Connection conn_service)throws ServiceException{
		boolean returnflag=false;
		try {
			String[] data1=data.split("##");
			if(data1.length>0){
				Charge charge=new Charge();
				charge.setStoreid(storeid);
				charge.setTranscode(tranCode);
				charge.setStatusid(SysConstant.RecordStatus.VALID);
				charge.setInputuserid(userContext.getLoginUser().getId());
				charge.setInputusername(userContext.getLoginUser().getUsername());
				charge.setModifyuserid(userContext.getLoginUser().getId());
				charge.setModifyusername(userContext.getLoginUser().getUsername());
				charge.setBuytype(SysConstant.ServiceBuyType.OTHER_BUY);
				charge.setBuyname(userContext.getLoginUser().getUsername());
				charge.setUsestatus(SysConstant.ServiceBuyUsestatus.VALID_BUY);
				//返回执行insertSysServiceByConn完成后的Connection对象
				sysServiceInfoService.updateSysServiceBuyInfo(charge,conn_service);
				//从redis中获取所有的服务及价格
				List<Charge> redisList=getChargeForList(storeid);
				for (int i = 0; i < data1.length; i++) {
					if(data1[i]!=null && !("").equals(data1[i])){
						StoreChargeManage storeChargeManage=new StoreChargeManage();
						String[] saveData=data1[i].split(":");
						String trantype=saveData[0];
						Long id=Long.valueOf(saveData[1]);
						String num=saveData[2];
						Charge chargeMap=null;
						for(Charge chargeList:redisList){
							if(chargeList.getServiceid()==id){
								chargeMap=chargeList;
								break;
							}
						}
						storeChargeManage.setMainid(charge.getId());
						storeChargeManage.setServiceid(Long.valueOf(id));
						storeChargeManage.setServicename(chargeMap.getServicename());
						storeChargeManage.setBuycount(Long.valueOf(num));
						storeChargeManage.setStatusid(SysConstant.RecordStatus.VALID);
						storeChargeManage.setInputusername(userContext.getLoginUser().getUsername());
						storeChargeManage.setModifyusername(userContext.getLoginUser().getUsername());
						if(Long.valueOf(trantype)==SysConstant.ChargeManage.MONTH){
							//按月
							String monthamount=saveData[3];
							String startdatestr=saveData[4];
							storeChargeManage.setBuytype(SysConstant.ChargeManage.CIRCLE);
							Date startdate=DataFormat.parseDate(startdatestr,DataFormat.DT_YYYY_MM_DD);
							Date enddate=DataFormat.calculationSubtractionDate(startdate,Integer.valueOf(num), 2);
							storeChargeManage.setStartdate(startdate);
							storeChargeManage.setEnddate(enddate);
							storeChargeManage.setUnitprice(DataFormat.parseNumber(monthamount));
							storeChargeManage.setStoreid(storeid);
							storeChargeManage.setTotalprice(MathUtils.mul(storeChargeManage.getBuycount(),storeChargeManage.getUnitprice()));
							//验证 该商户 是否已经购买 同一个服务在 同一个日期期间内的服务
//							Map<String, Object> map =new HashMap<String, Object>();
//							map.put("storeid", storeid);
//							map.put("serviceid",storeChargeManage.getServiceid());
//							map.put("buytype", storeChargeManage.getBuytype());
//							map.put("datetime",startdate);
//							boolean flag =sysServiceInfoService.findChargeManageForListByConn(map);
//							if(flag){
//								//如果存在有购买相同服务，将conn_service连接对象的事物回滚
//								conn_service.rollback();
//								userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.ordermessage.alert1"));
//							}else{
								//否则就新增购买的服务
								conn_service = sysServiceInfoService.insertSysServiceDetailByConn(storeChargeManage,conn_service);
//							}
						}else if(Long.valueOf(trantype)==SysConstant.ChargeManage.TRADESUM){
							//按笔数
							String monthamount=saveData[3];
							storeChargeManage.setBuytype(SysConstant.ChargeManage.TRADE);
							storeChargeManage.setUnitprice(DataFormat.parseNumber(monthamount));
							storeChargeManage.setTotalprice(MathUtils.mul(storeChargeManage.getBuycount(),storeChargeManage.getUnitprice()));
							conn_service = sysServiceInfoService.insertSysServiceDetailByConn(storeChargeManage,conn_service);
						}else{
							conn_service.rollback();
							System.out.println("未知收费方式不处理");
						}
					}
				}
				//最后都操作完毕，关闭连接对象
				sysServiceInfoService.setAutoCommitAndClose(conn_service);
				//判断是否有错误提示
				if (userContext.getMessageType() != 2) {
					// 修改金额
					SysServiceInfoService querySysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("mainid", charge.getId());
					map.put("storeid", storeid);
					double amount = querySysServiceInfoService.findTotalAmountByConn(map);
					Charge saveCharge = new Charge();
					saveCharge.setStoreid(storeid);
					saveCharge.setAmount(amount);
					saveCharge.setId(charge.getId());
					querySysServiceInfoService.updateSysServiceByConn(saveCharge);
					returnflag=true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnflag=false;
			new ServiceException("保存异常:"+e.getMessage());
		}finally{
			try {
				sysServiceInfoService.close(conn_service,null, null,null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return returnflag;
	}
	/*********************
	 * 服务管理-服务购买  支付按钮  修改数据
	 * 业务说明：1.将之后修改的在数据库进行逻辑删除，然后重新新增数据
	 * 		  2.结束日期 和 开始日期  不作 校验
	 * @param request
	 * @param response
	 * @param model
	 * @throws ServiceException
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/modifySaveService.json", method = {RequestMethod.GET,RequestMethod.POST})
	public void modifySaveService(HttpServletRequest request,HttpServletResponse response, Model model) throws ServiceException{
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,true);
		Connection conn=null;
		try {
			String mainid = request.getParameter("mainid");
			String data = request.getParameter("type");
			String tranCode = request.getParameter("tranCode");
			Long storeid = Long.parseLong(request.getParameter("storeid"));
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,false);
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("storeid", storeid);
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			hashMap.put("state", SysConstant.CommonApproveStatus.OK);
			DatabaseResource databaseResource = databaseBindingService.queryDatabaseBinding(hashMap);
			if(databaseResource == null){
				//商户若没挂接数据源，则提示
				userContext.setErrorMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
				throw new ServiceException(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
			}else{
				if(data!=null && !("").equals(data)){
					//先修改逻辑删除
					//删除
					hashMap.put("id", mainid);
					Charge charge=sysServiceInfoService.findResultOneByConn(hashMap);
					charge.setStatusid(SysConstant.RecordStatus.INVALID);
					charge.setModifyusername(userContext.getLoginUser().getUsername());
					conn=sysServiceInfoService.deteleSysServiceByConn(charge);
					conn=sysServiceInfoService.deteleSysServiceDetailByConn(charge,conn);
					//再新增
					boolean flag=saveService(data, storeid, tranCode, sysServiceInfoService,conn);
					if(flag){
						userContext.setCloseWindow(true);
						userContext.setInfoMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.success"));
					}else{
						userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.ordermessage.error"));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.ordermessage.error")+","+e.getMessage());
		}finally{
			try {
				sysServiceInfoService.close(conn,null, null,null);
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 服务管理-订单记录删除 
	 * 此方法还未完成  还需判断支付过
	 * @param request
	 * @param response
	 * @author yubaode
	 */
	@RequestMapping(value = "/dailyoperation/servicemanage/deleteServiceBuy.json", method ={RequestMethod.POST,RequestMethod.GET})
	public void deleteServiceBuy(HttpServletRequest request,HttpServletResponse response, Model model) {
		SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class,false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		Connection conn=null;
		try {
			DatabaseBindingService databaseBindingService = (DatabaseBindingService)IssTransactionContainer.getInstance(DatabaseBindingService.class,false);
			String mainid = request.getParameter("mainid");
			Long storeid = Long.parseLong(request.getParameter("storeid"));
			HashMap<String,Object> hashMap = new HashMap<String, Object>();
			hashMap.put("storeid", storeid);
			hashMap.put("statusid", SysConstant.RecordStatus.VALID);
			hashMap.put("state", SysConstant.CommonApproveStatus.OK);
			DatabaseResource databaseResource = databaseBindingService.queryDatabaseBinding(hashMap);
			if(databaseResource == null){
				//商户若没挂接数据源，则提示
				userContext.setErrorMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
				throw new ServiceException(MessageResourcesUtils.getMessage(request,"servicemessage.services.ordermessage.alert"));
			}else{
				hashMap.put("id", mainid);
				Charge charge=sysServiceInfoService.findResultOneByConn(hashMap);
				charge.setStatusid(SysConstant.RecordStatus.INVALID);
				charge.setModifyusername(userContext.getLoginUser().getUsername());
				conn=sysServiceInfoService.deteleSysServiceByConn(charge);
				conn=sysServiceInfoService.deteleSysServiceDetailByConn(charge,conn);
				//最后都操作完毕，关闭连接对象
				sysServiceInfoService.setAutoCommitAndClose(conn);
				userContext.setInfoMessage(MessageResourcesUtils.getMessage(request,"servicemessage.services.buymessage.success"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "servicemessage.services.buymessage.error")+","+e.getMessage());
		}finally{
			try {
				sysServiceInfoService.close(conn,null, null,null);
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	public List getChargeForList(Long storeid){
		SysServiceInfoService sysServiceInfoService = (SysServiceInfoService) IssTransactionContainer.getInstance(SysServiceInfoService.class, false);
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		hashMap.put("storeid", storeid);
		hashMap.put("statusid", SysConstant.RecordStatus.VALID);
		hashMap.put("checkstatus", SysConstant.CheckStatus.CHECKED);
		hashMap.put("businessstatus", SysConstant.CommonUsedStatus.START);
		//获得某个商户所有的商户收费管理数据
		List<Charge> storeChargeList = sysServiceInfoService.queryStoreChargeManageByStoreId(hashMap);
		//获得某个商户所有的收费管理的数据
		List<Charge> storeChargeAllList =  sysServiceInfoService.queryChargemanageByStoreId(hashMap);
		if(storeChargeList.size() == 0 || storeChargeList == null){
			storeChargeList = new ArrayList<Charge>();
		}
		List<Charge> list = new ArrayList<Charge>();
		if(storeChargeAllList !=null && storeChargeAllList.size() !=0){
			for(Charge charge:storeChargeAllList){
				for(Charge tmp:storeChargeList){
					if(charge.getServiceid() == tmp.getServiceid()){
						charge.setIsmonth(tmp.getIsmonth());
						charge.setMonthprice(tmp.getMonthprice());
						charge.setIsproposed(tmp.getIsproposed());
						charge.setProposedprice(tmp.getProposedprice());
					}
				}
				list.add(charge);
			}
		}
		return list;
	}
}

